<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Log;

class Push extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();
        if ($this->request->isGet()) {
            $this->assign('institute', model('user')->field('institute')->group('institute')->select());
            $this->assign('jobTitle', model('user')->field('job_title')->group('job_title')->select());
        }
    }

    public function index()
    {
        $param = $this->request->param();
        $where = [];
        $whereOr = [];
        if (isset($param['name'])) {
            $whereOr['user_name'] = ['like', "%" . $param['name'] . "%"];
            $whereOr['email'] = ['like', "%" . $param['name'] . "%"];
            $whereOr['phone'] = ['like', "%" . $param['name'] . "%"];
        }
        if (isset($param['institute'])) {
            $where['institute'] = $param['institute'];
        }
        if (isset($param['job_title'])) {
            $where['job_title'] = $param['job_title'];
        }
        if (isset($param['sendFrom']) && isset($param['sendTo'])) {
            $param['sendFrom'] .= " 00:00:00";
            $param['sendTo'] .= " 23:59:59";
            $where['create_time'] = array('between', array($param['sendFrom'], $param['sendTo']));
        } else {
            if (isset($param['sendFrom'])) {
                $param['sendFrom'] .= " 00:00:00";
                $where['create_time'] = array('egt', $param['sendFrom']);
            }
            if (isset($param['sendTo'])) {
                $param['sendTo'] .= " 23:59:59";
                $where['create_time'] = array('elt', $param['sendTo']);
            }
        }
        $list = model('user')
            ->whereOr(function ($query) use ($whereOr) {
                $query->whereOr($whereOr);
            })
            ->where(function ($query) use ($where) {
                $query->where($where);
            })
            ->paginate(config('page_number'), false, ['query' => $param]);
        return $this->fetch('index', ['list' => $list]);
    }

    public function toPush()
    {
        $param = $this->request->param();
        $template = '';
        if (!empty($param['template'])) {
            $template = $param['template'];
        }
        $projectRecommendId = '';
        if (!empty($param['projectRecommendId'])) {
            $projectRecommendId = $param['projectRecommendId'];
        }
        return $this->fetch('push', [
            'data' => $param['userId'],
            'template' => $template,
            'projectRecommendId' => $projectRecommendId
        ]);
    }

    public function push()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $num = 0;
            $userIds = [];
            if (strpos($param['user_id'], ',') !== false) {
                $userIds = explode(',', $param['user_id']);
            } else {
                $userIds[0] = $param['user_id'];
            }
            $condition = null;
            if (!empty($param['condition'])) {
                $condition = $param['condition'];
            }
            if ($param['template'] == 4 && $condition == null) {
                $this->error('请选择审核不通过条件');
            }
            foreach ($userIds as $v) {
                $user = model('user')->where('id', '=', $v)->find();
                if(empty($user) || $param['template'] == 4) {
                    $user = db('scholar')->alias('s')
                        ->join('user u', 's.kid = u.user_no', 'left')
                        ->field('u.*')
                        ->where('s.id', '=', $v)
                        ->find();
                    if (empty($user)) {
                        continue;
                    }
                }
                $push = [];
                $push['id'] = null;
                $push['user_id'] = $v;
                $push['template'] = $param['template'];
                $push['channel'] = $param['channel'];
                $push['type'] = $param['type'];
                $push['type'] = $param['type'];
                $push['status'] = 0;
                if ($param['type'] == 1) {
                    $push['status'] = 1;
                    $push['send_time'] = date("Y-m-d H:i:s");
                }
                if ($param['type'] == 2 && empty($param['send_time'])) {
                    $this->error('请选择定时发送时间');
                }
                $push['create_time'] = date("Y-m-d H:i:s");
                if ($param['template'] == 4) {
                    $param['content'] = str_replace('{check}', $condition, $param['content']);
                }
                $push['content'] = str_replace('{phone}', substr($user['phone'], strlen($user['phone']) - 4, 4), str_replace('{user}', $user['user_name'], $param['content']));
                if (db('push_record')->insert($push) == true) {
                    $title = '其他消息通知';
                    if ($param['template'] == 1) {
                        $title = '名片创建通知';
                    } elseif ($param['template'] == 2) {
                        $title = '成果认领通知';
                    }  elseif ($param['template'] == 3) {
                        $title = '项目推送';
                    } elseif ($param['template'] == 4) {
                        $title = '学者审核推送';
                        $param['content'] = str_replace('{check}', $condition, $param['content']);
                    }
                    // TODO 发送消息
                    if ($param['channel'] == 1) {

                    } elseif ($param['channel'] == 2) {
                        send_email($user['email'], $title, $param['content']);
                    } elseif ($param['channel'] == 3) {
                        send_email($user['email'], $title, $param['content']);
                    }

                    if ($param['template'] == 4) {
                        db('scholar')->where([
                            'kid' => $user['user_no']
                        ])->update([
                            'is_check' => 2
                        ]);
                    }
                    $num++;
                }
            }
            if (!empty($param['projectRecommendId'])) {
                $projectRecommend = model('projectRecommend')->where('id', '=', $param['projectRecommendId'])->find();
                if (!empty($projectRecommend)) {
                    $people = explode(',', $projectRecommend['notice_people']);
                    $add = 0;
                    foreach ($userIds as $v) {
                        if (in_array($v, $people) === false) {
                            $people[sizeof($people) + $add] = $v;
                            $add++;
                        }
                    }
                    db('projectRecommend')->where([
                        'id' => $param['projectRecommendId']
                    ])->update([
                        'notice_people' => implode(',', $people)
                    ]);
                }
            }

            $successNum = $num;
            $failNum = sizeof($userIds) - $num;
            insert_admin_log('添加了推送消息');
            $this->success('添加成功' . $successNum . '条，失败' . $failNum . '条', url('admin/push/index'));
        }
        return $this->fetch('push', ['data' => $param['userId']]);
    }

    public function rePush()
    {
        $param = $this->request->param();
        $record = model('pushRecord')->where('id', '=', $param['id'])->find();
        if (empty($record)) {
            $this->error('参数错误');
        }
        $user = model('user')->where('id', '=', $record['user_id'])->find();
        if (empty($user)) {
            $this->error('参数错误');
        }
        $title = '其他消息通知';
        if ($record['template'] == 1) {
            $title = '名片创建通知';
        } elseif ($record['template'] == 2) {
            $title = '成果认领通知';
        }
        // TODO 发送消息
        if ($record['channel'] == 1) {

        } elseif ($record['channel'] == 2) {
//                        send_email($user['email'], $title, $record['content']);
            send_email('dmfh294597341@163.com', $title, $record['content']);
        } elseif ($record['channel'] == 3) {
            send_email($user['email'], $title, $record['content']);
        }
        // 添加一条新记录
        $newRecord = [];
        $newRecord['user_id'] = $record['user_id'];
        $newRecord['template'] = $record['template'];
        $newRecord['channel'] = $record['channel'];
        $newRecord['content'] = $record['content'];
        $newRecord['type'] = 1;
        $newRecord['status'] = 1;
        $newRecord['send_time'] = date("Y-m-d H:i:s");
        $newRecord['create_time'] = date("Y-m-d H:i:s");
        if ($this->insert('pushRecord', $newRecord, false) === true) {
            insert_admin_log('添加了推送消息');
            $this->success('重发成功', url('admin/push/record'));
        } else {
            $this->error($this->errorMsg);
        }
        $this->error('重发失败');
    }

    public function cronPush()
    {
        Log::write('定时任务开始执行');
        $list = model('pushRecord')
            ->where('status', '=', 0)
            ->where('send_time', '<=', date("Y-m-d H:i:s"))
            ->select();
        if (empty($list)) {
            return;
        }
        foreach ($list as $msg) {
            $user = model('user')->where('id', '=', $msg['user_id'])->find();
            if (empty($user)) {
                continue;
            }
            $title = '其他消息通知';
            if ($msg['template'] == 1) {
                $title = '名片创建通知';
            } elseif ($msg['template'] == 2) {
                $title = '成果认领通知';
            }
            if ($msg['channel'] == 1) {

            } elseif ($msg['channel'] == 2) {
//                        send_email($user['email'], $title, $param['content']);
                send_email('dmfh294597341@163.com', $title, $msg['content']);
            } elseif ($msg['channel'] == 3) {
                send_email($user['email'], $title, $msg['content']);
            }
            $msg['status'] = 1;
            $this->update('pushRecord', $msg, false);
        }
    }

    public function record()
    {
        $param = $this->request->param();
        $where = [];
        $whereOr = [];
        if (isset($param['name'])) {
            $whereOr['user_name'] = ['like', "%" . $param['name'] . "%"];
            $whereOr['email'] = ['like', "%" . $param['name'] . "%"];
            $whereOr['phone'] = ['like', "%" . $param['name'] . "%"];
        }
        if (isset($param['institute'])) {
            $where['institute'] = $param['institute'];
        }
        if (isset($param['job_title'])) {
            $where['job_title'] = $param['job_title'];
        }
        if (isset($param['sendFrom']) && isset($param['sendTo'])) {
            $param['sendFrom'] .= " 00:00:00";
            $param['sendTo'] .= " 23:59:59";
            $where['send_time'] = array('between', array($param['sendFrom'], $param['sendTo']));
        } else {
            if (isset($param['sendFrom'])) {
                $param['sendFrom'] .= " 00:00:00";
                $where['send_time'] = array('egt', $param['sendFrom']);
            }
            if (isset($param['sendTo'])) {
                $param['sendTo'] .= " 23:59:59";
                $where['send_time'] = array('elt', $param['sendTo']);
            }
        }
        $list = db('push_record')->alias('pr')
            ->join('user u', 'pr.user_id = u.id', 'left')
            ->field('pr.id as id, u.user_name, u.phone, u.email, pr.send_time, pr.content')
            ->whereOr(function ($query) use ($whereOr) {
                $query->whereOr($whereOr);
            })
            ->where(function ($query) use ($where) {
                $query->where($where);
            })
            ->order('send_time desc')
            ->paginate(config('page_number'), false, ['query' => $param]);
        return $this->fetch('record', ['list' => $list]);
    }


}
